package com.syp.auth.service.validator.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.syp.auth.dao.po.AppEntity;
import com.syp.auth.dao.repository.AppRepository;
import com.syp.auth.domain.ValidateResult;
import com.syp.auth.export.common.GeneralAccessVo;
import com.syp.auth.export.common.GeneralUserVo;
import com.syp.auth.export.common.GorgeousParameters;
import com.syp.auth.export.common.TokenSecurity;
import com.syp.auth.service.validator.SigninError;
import com.syp.auth.service.validator.SigninValidatorI;
import com.syp.auth.service.validator.SigninVerifyStyle;

@Service
public class SigninValidatorImpl implements SigninValidatorI {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	@Autowired
	private AppRepository appRepository;

	@Override
	public ValidateResult validate(GeneralUserVo guser, GeneralAccessVo gaccess) {
		ValidateResult vr = new ValidateResult(true);

		SigninError se = null;
		// 校验必录项
		if (StringUtils.isEmpty(guser.getUserCode())) {
			se = SigninError.usernameMustNotEmpty;
		} else if (StringUtils.isEmpty(guser.getPassword())) {
			se = SigninError.passwordMustNotEmpty;
		} else if (StringUtils.isEmpty(gaccess.getSid())) {
			se = SigninError.tokenMustNotEmpty;
		} else if (StringUtils.isEmpty(gaccess.getApp())) {
			se = SigninError.appMustNotEmpty;
		} else {
			String appCode = gaccess.getApp();
			AppEntity app = appRepository.getByAppCode(appCode);
			SigninVerifyStyle svs = app.getVerifyStyle() == null ? SigninVerifyStyle.NONE : SigninVerifyStyle.get(app.getVerifyStyle());
			switch (svs) {
			case NONE: {
				break;
			}
			case IVC: {
				if (StringUtils.isEmpty(gaccess.getVc())) {
					se = SigninError.ivcMustNotEmpty;
				} else {// 校验验证码有效性
					String token = TokenSecurity.getInstunce().decrypt(gaccess.getSid());
					final String key = GorgeousParameters.IVC_PREFIX + token;
					final String ivc = this.stringRedisTemplate.opsForValue().get(key);
					if (StringUtils.isEmpty(ivc)) {
						se = SigninError.ivcExpired;
					} else if (!gaccess.getVc().equalsIgnoreCase(ivc)) {
						se = SigninError.ivcUncheck;
					} else if (gaccess.getVc().equalsIgnoreCase(ivc)) {// 验证码配置通过即删除
						stringRedisTemplate.delete(key);
					}
				}
				break;
			}
			}
		}

		if (se != null) {
			vr.valid(false).ecode(se.name()).emsg(se.getEmsg());
		}

		return vr;
	}

}
